<template>
    <div class="register_container">
        <el-form class="register_form" :model="registerFormData" :rules="rules" ref="ruleFormRef">
            <h2>注册账号</h2>

            <el-form-item prop="name">
                <el-input
                    prefix-icon="User"
                    v-model="registerFormData.name"
                    type="text"
                    placeholder="用户名"
                ></el-input>
            </el-form-item>
            <el-form-item prop="email">
                <el-input
                    prefix-icon="Message"
                    v-model="registerFormData.email"
                    type="text"
                    placeholder="邮箱"
                ></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input
                    type="password"
                    prefix-icon="Lock"
                    v-model="registerFormData.password"
                    show-password
                    placeholder="密码"
                ></el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
                <el-input
                    type="password"
                    prefix-icon="Lock"
                    v-model="registerFormData.confirmPassword"
                    show-password
                    placeholder="确认密码"
                ></el-input>
            </el-form-item>
            <el-form-item prop="code">
                <div class="code_item">
                    <el-input
                        prefix-icon="Key"
                        v-model="registerFormData.code"
                        type="text"
                        placeholder="邮箱验证码"
                    ></el-input>
                    <code-button :email="registerFormData.email" :formRef="ruleFormRef" type="register"></code-button>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button
                    :loading="loading"
                    type="primary"
                    size="default"
                    @click="register(ruleFormRef as FormInstance)"
                >
                    注册
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button :loading="loading" type="primary" size="default" @click="goLogin">
                    已有账号？前往登录
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
import { ref, reactive } from "vue";
import { reqRegister } from "@/api/user";
import { ElNotification } from "element-plus";
import { getTime } from "@/utils/time";
import { isEmpty } from "@/utils/tools/isEmpty";
import { isValidEmail } from "@/utils/tools/verify.ts";
// 引入用户相关的小仓库
import useUserStore from "@/store/modules/user";
// 引入类型
import type { registerForm } from "@/api/user/type";
import type { FormInstance, FormRules } from "element-plus";
// 获取表单实例
const ruleFormRef = ref<FormInstance>();
// 获取表单数据
const registerFormData = reactive<registerForm>({
    name: "",
    email: "",
    password: "",
    confirmPassword: "",
    code: "",
});
// 定义校验规则
// 校验邮箱
const validateEmail = (_rule: any, value: string, callback: any) => {
    if (isEmpty(value)) {
        return callback(new Error("邮箱不能为空"));
    }
    if (!isValidEmail(value)) {
        return callback(new Error("请输入正确的邮箱"));
    }
    callback();
};
// 校验密码
const validatePassword = (_rule: any, value: string, callback: any) => {
    if (isEmpty(value)) {
        return callback(new Error("密码不能为空"));
    }
    if (value.length < 6 || value.length > 30) {
        return callback(new Error("密码长度应在6-30之间"));
    }
    callback();
};
// 校验确认密码
const validateConfirmPassword = (_rule: any, value: string, callback: any) => {
    if (isEmpty(value)) {
        return callback(new Error("确认密码不能为空"));
    }
    if (value !== registerFormData.password) {
        return callback(new Error("两次输入的密码不一致"));
    }
    callback();
};
// 定义表单校验规则
const rules = reactive<FormRules<registerForm>>({
    name: [
        { required: true, message: "用户名不能为空", trigger: "blur" },
        { min: 1, max: 30, message: "长度应该在30个字符以内", trigger: "blur" },
    ],
    email: [{ validator: validateEmail, trigger: "blur" }],
    password: [{ validator: validatePassword, trigger: "blur" }],
    confirmPassword: [{ validator: validateConfirmPassword, trigger: "blur" }],
    code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
});

// 定义加载态
const loading = ref<boolean>(false);

// 前往登录路由
// 获取路由器
let $router = useRouter();
let $route = useRoute();
const goLogin = () => {
    $router.push({ path: "/login", query: { redirect: $route.query.redirect } });
    return;
};

// 定义注册方法
// 获取仓库实例
let userStore = useUserStore();
const register = ($FormEl: FormInstance) => {
    // 二次保存账号密码
    const email = registerFormData.email;
    const password = registerFormData.password;
    // 登录时应该对表单进行校验
    $FormEl
        // 发起字段校验
        .validate()
        .then(
            // 验证通过则发起注册请求
            () => {
                loading.value = true;
                return reqRegister(registerFormData);
            },
            () => {
                return Promise.reject(new Error("数据不符合要求"));
            },
        )
        .then((res) => {
            // 如果code不等于200则注册失败
            if (res.code !== 200) {
                return Promise.reject(new Error(res.data));
            }
            // 注册成功后直接登录
            return userStore.userLogin({
                email,
                password,
                loginWay: "password",
            });
        })
        .then(
            () => {
                // 重定向到指定页面
                $router.push({
                    path: ($route.query.redirect as string) || "/",
                });
                // 弹出通知框告知登录成功
                ElNotification({
                    type: "success",
                    title: `Hi,${getTime()}好`,
                    message: "欢迎回来",
                });
            },
            // 通知登录失败
            (error) => {
                ElNotification({
                    type: "error",
                    message: (error as Error).message,
                });
            },
        )
        .finally(() => {
            loading.value = false;
        });
};
</script>

<style lang="scss" scoped>
.register_container {
    width: 100%;
    height: 100vh;
    background: url("@/assets/images/background.png") no-repeat;
    background-size: cover;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .register_form {
        width: 20%;
        background-color: rgba(59, 55, 113, 0.4);
        background-size: cover;
        padding: 40px;

        h2 {
            color: white;
            font-size: 20px;
            margin: 20px 0px;
        }

        .el-form-item {
            width: 80%;
            margin-left: auto;
            margin-right: auto;

            .code_item {
                width: 100%;
                display: flex;
                justify-content: space-between;
                flex-wrap: nowrap;

                .el-input {
                    flex-basis: 50%;
                    flex-grow: 1;
                }

                :deep(.get_code_btn) {
                    flex-basis: 30%;
                    flex-grow: 1;
                    margin-left: 20px;
                }
            }

            .el-button {
                width: 100%;
            }
        }
    }
}
</style>
